package shop

import (
	"context"
	"fast-boot/app/model"
	"github.com/hwUltra/fb-tools/gormx"
	"github.com/jinzhu/copier"

	"fast-boot/app/api/admin/internal/svc"
	"fast-boot/app/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CategoryListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 类型列表
func NewCategoryListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CategoryListLogic {
	return &CategoryListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CategoryListLogic) CategoryList(req *types.PmsCategoryListReq) (resp []*types.PmsCategory, err error) {
	m := model.PmsCategoryModel{}
	items := make([]*model.PmsCategoryModel, 0)
	l.svcCtx.GormClient.GormDb.Model(m).
		Scopes(
			gormx.Paginate(int(req.PageNum), int(req.PageSize)),
			m.WithShopId(req.ShopId),
			m.WithKeywords(req.Keywords)).
		Order("sort asc,id asc").Find(&items)

	resp = makeTreeCategoryList(items, 0)
	return resp, nil
}

func makeTreeCategoryList(list []*model.PmsCategoryModel, parentID int64) []*types.PmsCategory {
	res := make([]*types.PmsCategory, 0)
	for _, item := range list {
		if item.ParentId == parentID {
			var it types.PmsCategory
			_ = copier.Copy(&it, item)
			it.Children = makeTreeCategoryList(list, item.Id)
			res = append(res, &it)
		}
	}
	return res
}
